//
//  JSFileUtils.m
//  FastTest
//
//  Created by Song Lanlan on 13-9-27.
//  Copyright (c) 2013年 tiantian. All rights reserved.
//

#import "JSFileUtils.h"
#import "zipzap.h"

@implementation JSFileUtils

+(void)iterateFileInDir:(NSString*)dirPath doWithFile:(void (^)(NSString *filePath))block{
  NSFileManager* fileManager = [NSFileManager defaultManager];
  NSArray *files = [fileManager subpathsOfDirectoryAtPath:dirPath error:nil];
  if (files) {
    for (NSString *path in files) {
      block(path);
    }
  }
}

@end


@implementation NSURL(JSFileUtils)

-(void)jsUnzipToDir:(NSString*)dirPath
       onCompletion:(void (^)(NSDictionary *unzippedFiles))block{
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSURL *zipURL = self;
    NSURL *targetDir = [NSURL fileURLWithPath:dirPath];
    
    NSFileManager* fileManager = [NSFileManager defaultManager];
    ZZArchive* archive = [ZZArchive archiveWithContentsOfURL:zipURL];
    NSMutableDictionary *zippedFiles = [NSMutableDictionary dictionaryWithCapacity:5];// by estimate
    for (ZZArchiveEntry* entry in archive.entries){
      NSURL* targetPath = [targetDir URLByAppendingPathComponent:entry.fileName];
      
      // collect all the files
      if (!(entry.fileMode & S_IFDIR)){
        zippedFiles[[entry.fileName stringByReplacingOccurrencesOfRegex:@".*/"
                                                             withString:@""]] = targetPath.relativePath;
      }
      
      if (entry.fileMode & S_IFDIR){
        // check if directory bit is set
        [fileManager createDirectoryAtURL:targetPath
              withIntermediateDirectories:YES
                               attributes:nil
                                    error:nil];
      }
      else{
        // Some archives don't have a separate entry for each directory and just
        // include the directory's name in the filename. Make sure that directory exists
        // before writing a file into it.
        [fileManager createDirectoryAtURL:[targetPath URLByDeletingLastPathComponent]
              withIntermediateDirectories:YES
                               attributes:nil
                                    error:nil];
        
        [entry.data writeToURL:targetPath
                    atomically:NO];
      }
    }
    
    if (block) {
      dispatch_async(dispatch_get_main_queue(), ^{
        block(zippedFiles);
      });
    }
  });
}



@end
